#!/usr/bin/python2
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab:fileencoding=utf-8

from __future__ import absolute_import
from __future__ import print_function
#from __future__ import unicode_literals
from __future__ import division

'''
        @author: msune,lbergesio, omoya

    Simple example Policy Engine simualting a Server interface (e.g. rpc)

'''

from threading import Thread, Lock

from pelib.ruletable import RuleTable

from interface import interface

'''
    Uses pyPElib to build ONE RuleTable instance to apply policies to a certain scope (in this example, the interface).


'''

_instance = None

_mutex = Lock()


#Mappings contains the basic association between keywords and objects, functions or static values
#Note that these mappings are ONLY defined by the lib user (programmer)
_mappings = {"vm.Name":"['actions'][0]['vm']['Name']",
        "vm.RAM":"metaObj['actions'][0]['vm']['RAM']",
        "vm.HDD":"metaObj['actions'][0]['vm']['HDD']",
        "vm.OS":"metaObj['actions'][0]['vm']['OS']",
        "user.id":interface.getUserId,
        "log":"utils.logger.get_logger()"}

def get_policy():
    global _instance
    with _mutex:
        if not _instance:
            print ("Loading ruletable from File...")
            _instance = RuleTable.loadOrGenerate('mypolicyengine', _mappings, "RegexParser", "RAWFile", True, fileName="database/myPolicyEngine.db") #Loading from file backend
    return _instance

def verify(obj):
    return get_policy().evaluate(obj)

def dump():
    return get_policy().dump()
